<template>
  <view class="favorites-page">
    <!-- 自定义导航栏 -->
    <u-navbar
      title="我的收藏"
      :border="false"
      bgColor="#FFFFFF"
      titleColor="#333333"
      :titleStyle="{ fontSize: '36rpx', fontWeight: '500' }"
      leftIcon="arrow-left"
      placeholder
      @leftClick="goBack"
    >
    </u-navbar>
    
    <!-- 切换按钮区域 -->
    <view class="filter-section">
      <view class="filter-tabs">
        <view 
          class="filter-tab" 
          :class="{ active: activeTab === 'all' }"
          @click="switchTab('all')"
        >
          <text class="tab-text">全部</text>
        </view>
        <view 
          class="filter-tab" 
          :class="{ active: activeTab === 'jobs' }"
          @click="switchTab('jobs')"
        >
          <text class="tab-text">岗位</text>
        </view>
      </view>
      
      <!-- 更新按钮 -->
      <view class="update-section">
        <u-button
          text="更新岗位"
          size="small"
          type="primary"
          @click="updateJobs"
          :customStyle="{ 
            backgroundColor: 'var(--u-primary)', 
            borderColor: 'var(--u-primary)',
            fontSize: '24rpx',
            padding: '8rpx 20rpx',
            borderRadius: '20rpx'
          }"
        ></u-button>
      </view>
    </view>
    
    <!-- 岗位列表 -->
    <view class="job-list">
      <view 
        class="job-card" 
        v-for="(job, index) in filteredJobs" 
        :key="index"
        @click="goToJobDetail(job)"
      >
        <!-- 岗位标题和薪资 -->
        <view class="job-header">
          <text class="job-title">{{ job.title }}</text>
          <text class="job-salary">{{ job.salary }}</text>
        </view>
        
        <!-- 标签 -->
        <view class="job-tags">
          <view 
            class="tag-item" 
            v-for="(tag, tagIndex) in job.tags" 
            :key="tagIndex"
            :class="tag.type"
          >
            <text class="tag-text">{{ tag.text }}</text>
          </view>
        </view>
        
                 <!-- 还招岗位展示 -->
         <view v-if="job.positionName" class="job-positions">
           <text class="positions-label">还招：</text>
           <text class="positions-text">{{ job.positionName }}</text>
         </view>
        
        <!-- 企业名称+地址 -->
        <view class="job-location">{{ job.location }}</view>
        
        <!-- 日期 -->
        <view class="job-date">
          <text class="date-text">{{ job.date }}</text>
        </view>
      </view>
    </view>
    
    <!-- 空状态 -->
    <view v-if="filteredJobs.length === 0" class="empty-state">
      <u-icon name="star" size="80" color="#CCCCCC"></u-icon>
      <text class="empty-text">暂无收藏内容</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { userApi } from '@/api/api-helper.js'
import { userStore } from '@/stores/userStore'

// 当前激活的标签
const activeTab = ref('all')

// 收藏數據
const favoritesData = ref<any[]>([])

onMounted(async () => {
  await fetchFavorites()
})

async function fetchFavorites() {
  try {
    const openId = userStore.getOpenId()
    if (!openId) return
    // 使用收藏列表接口
    const res: any = await userApi.getFollowList({ openId, currentPage: 1, pageSize: 50 })
    if (res && res.code === 200) {
      const list = (res.data && res.data) || []
      favoritesData.value = list.map((item: any) => ({
        id: item.hireRecruitUseId || item.id,
        type: 'jobs',
        title: item.hireName || item.title || '收藏岗位',
        salary: item.workPrice || item.salary || '面议',
        tags: parseTags(item.enterpriseLabel || ''),
        date: item.hireStartDate || item.createdAt || '',
        customerName: item.customerName,
        address: item.address,
        location: formatLocation(item.customerName, item.address),
        positionName: item.positionName || ''
      }))
    }
  } catch (e) {
    console.warn('獲取收藏列表失敗', e)
  }
}

function parseTags(enterpriseLabel: string) {
  if (!enterpriseLabel) return []
  try {
    let tags: any[] = []
    if (enterpriseLabel.startsWith('[')) tags = JSON.parse(enterpriseLabel)
    else tags = enterpriseLabel.split(',').map(t => t.trim())
    return tags.map(t => ({ text: t, type: 'primary' }))
  } catch {
    return []
  }
}

function formatLocation(customerName: string, address: any) {
  if (!customerName && !address) return '未知地点'
  let location = customerName || ''
  if (address) {
    if (typeof address === 'string') {
      location = location ? `${location} ${address}` : address
    } else if (address.province || address.city) {
      if (address.province && address.city) {
        location += `${location ? ' ' : ''}${address.province}-${address.city}`
      } else if (address.province) {
        location += `${location ? ' ' : ''}${address.province}`
      } else if (address.city) {
        location += `${location ? ' ' : ''}${address.city}`
      }
    }
  }
  return location
}

// 根据当前标签过滤数据
const filteredJobs = computed(() => {
  if (activeTab.value === 'all') {
    return favoritesData.value
  }
  return favoritesData.value.filter(item => item.type === activeTab.value)
})

// 返回
const goBack = () => {
  uni.navigateBack()
}

// 切换标签
const switchTab = (tab: string) => {
  activeTab.value = tab
}

// 更新岗位
const updateJobs = () => {
  fetchFavorites()
}

// 跳转到岗位详情
const goToJobDetail = (job: any) => {
  if (job.type === 'jobs') {
    uni.navigateTo({
      url: `/pages/job-details/job-details?jobId=${job.id}`
    })
  } else {
    uni.showToast({
      title: '商品详情功能开发中',
      icon: 'none'
    })
  }
}
</script>

<style lang="scss" scoped>
.favorites-page {
  min-height: 100vh;
  background-color: #F5F5F5;
}

.header-icons {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.filter-section {
  background-color: #FFFFFF;
  padding: 20rpx 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid #F0F0F0;
}

.filter-tabs {
  display: flex;
  gap: 20rpx;
}

.filter-tab {
  padding: 12rpx 24rpx;
  border-radius: 20rpx;
  background-color: #F5F5F5;
  transition: all 0.3s;
  
  &.active {
    background-color: var(--u-primary);
    
    .tab-text {
      color: #FFFFFF;
    }
  }
}

.tab-text {
  font-size: 28rpx;
  color: #666666;
  font-weight: 500;
}

.update-section {
  display: flex;
  align-items: center;
}

.job-list {
  padding: 20rpx;
}

.job-card {
  background-color: #FFFFFF;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.job-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20rpx;
}

.job-title {
  flex: 1;
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
  line-height: 1.4;
  margin-right: 20rpx;
}

.job-salary {
  font-size: 28rpx;
  color: var(--u-red);
  font-weight: 600;
  white-space: nowrap;
}

.job-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  margin-bottom: 20rpx;
}

.job-positions {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20rpx;
  
  .positions-label {
    font-size: 24rpx;
    color: #666666;
    margin-right: 8rpx;
    flex-shrink: 0;
  }
  
  .positions-text {
    font-size: 24rpx;
    color: #333333;
    line-height: 1.4;
    flex: 1;
  }
}

.job-location {
  font-size: 26rpx;
  color: #999999;
  margin-bottom: 12rpx;
}

.tag-item {
  padding: 6rpx 12rpx; /* 縮小標籤內邊距 */
  border-radius: 8rpx;
  border: 1rpx solid;
  display: inline-flex; /* 讓內容垂直置中 */
  align-items: center;
  line-height: 1; /* 消除行高影響 */
  
  &.primary {
    background-color: var(--u-primary-plain-disabled);
    border-color: var(--u-primary);
    
    .tag-text {
      color: var(--u-primary);
    }
  }
  
  &.secondary {
    background-color: #F5F5F5;
    border-color: #DDDDDD;
    
    .tag-text {
      color: #666666;
    }
  }
}

.tag-text {
  font-size: 20rpx; /* 縮小標籤字級 */
  font-weight: 500;
  line-height: 1; /* 與容器對齊，避免上下不居中 */
}

.job-date {
  text-align: left;
}

.date-text {
  font-size: 24rpx;
  color: #999999;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-text {
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #999999;
}
</style> 